package com.zhanghe.study.verificationcode.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码生成工具
 */
public class VaildDataUtil {

    public static BufferedImage getValidDataCode(String content){
        // 宽高
        int width = 100;
        int higth = 30;

        BufferedImage buf = new BufferedImage(width,higth, BufferedImage.TYPE_INT_RGB);

        // 创建画布
        Graphics2D gs = buf.createGraphics();
        // 设置画布颜色
        gs.setColor(getRandomColor(0,50));
        // 绘制矩形
        gs.fillRect(0,0,width,higth);

        // 干扰线
        Random random = new Random();
        for(int i = 0;i<20;i++){
            gs.setColor(getRandomColor(100,200));
            // 防止起点终点相同
            int x1 = random.nextInt(50);
            int y1 = random.nextInt(20);
            int x2 = x1 + random.nextInt(50);
            int y2 = y1 + random.nextInt(20);
            gs.drawLine(x1,y1,x2,y2);
        }

        // 噪点
        float rate = 0.1f;// 噪点率
        int area = (int) (rate * width*higth);
        for(int i=0;i<area;i++){
            int x = random.nextInt(width);
            int y = random.nextInt(higth);
            buf.setRGB(x,y,random.nextInt(255));
        }

        // 字体
        Font font = new Font("宋体",Font.BOLD,25);
        gs.setFont(font);
        // 字体颜色
        gs.setColor(getRandomColor(100,255));
        gs.drawString(content,10,30);
        try {
            ImageIO.write(buf,"png",new File("test.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭画布
        gs.dispose();
        // 使用随机色
        return buf;
    }

    /**
     * 生成随机颜色
     * 范围0~255
     * @param from 起始
     * @param to 结束
     * @return
     */
    public static Color getRandomColor(int from,int to){
        if(from < 0 || to > 255){
            throw new RuntimeException("超出颜色范围");
        }
        Random random = new Random();
        // 生成rgb
        int r = from + random.nextInt(to-from);
        int g = from + random.nextInt(to-from);
        int b = from + random.nextInt(to-from);
        return new Color(r,g,b);
    }

    public static void main(String[] args) {
        getValidDataCode("7640");
    }
}
